//
//  MQStatusListViewModel.swift
//  MQWeibo
//
//  Created by 毛强 on 16/1/1.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SDWebImage

class MQStatusListViewModel: NSObject {
    // 视图模型里面引用的数据
    var statuses: [MQStatusViewModel]?
    
    func loadData(isPullUp:Bool, completion: (isSuccessed: Bool)->()){
        var maxId:Int64 = 0
        var sinceId:Int64 = 0
        
        if isPullUp{
            maxId = statuses?.last?.status?.id ?? 0
            if maxId > 0{
                maxId -= 1
            }
        }else{
            // 下拉刷新
            sinceId = statuses?.first?.status?.id ?? 0
        }
        
        // 定义请求地址与参数
        let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
        
        let params = [
            "access_token": MQUserAccountViewModel.sharedViewModel.accessToken!,
            "max_id":"\(maxId)",
            "since_id":"\(sinceId)"
        ]
        
        // 发送请求
        MQNetWorkTools.sharedTools.request(urlString: urlString, parameters: params) { (response, error) -> () in
            
            if error != nil {
                print(error)
                // 请求失败，回调：不成功
                completion(isSuccessed: false)
                return
            }
            
            guard let responseDict = response as? [String: AnyObject] else {
                completion(isSuccessed: false)
                print("返回数据不是字典")
                return
            }
            
            // 字典转模型
            let statusDicts = responseDict["statuses"]! as! [[String: AnyObject]]
            // 定义监听数据，保存转成功的模型
            var tempArray: [MQStatusViewModel] = [MQStatusViewModel]()
            
            if self.statuses == nil{
                self.statuses = [MQStatusViewModel]()
            }
            
            // 遍历字典转模型
            for dict in statusDicts {
                let status = MQStatus(dict: dict)
                
                // 初始化视图模型
                let statusViewModel = MQStatusViewModel()
                // 设置值
                statusViewModel.status = status
                // 把模型添加到数组里面
                tempArray.append(statusViewModel)
            }
            
            if isPullUp{
            
                // 赋值
                self.statuses! += tempArray
            }else{
                // 下拉刷新的数据
                print("下拉刷新出\(tempArray.count)条数据")
                self.statuses = tempArray + self.statuses!
            }
            
            self.cacheSingleImage(tempArray, completion: completion)
            // 刷新数据
//            completion(isSuccessed: true)
        }
    }
    /// 缓存单张图片
    ///
    /// - parameter dataArray: 要缓存的列表数据
    private func cacheSingleImage(dataArray: [MQStatusViewModel], completion: (isSuccessed: Bool)->()){
        
        var dataLength = 0
        
        // 创建组
        let group = dispatch_group_create()
        
        for viewModel in dataArray {
            
            // 判断 当前 viewModel 里面的图片是否是单张
            if viewModel.picUrls?.count != 1 {
                // 不执行任何操作，继续下一次循环
                continue
            }
            
            let urlString = viewModel.picUrls!.first!.thumbnail_pic!
            print(urlString)
            let url = NSURL(string: urlString)
            
            // 入组，会监听后续的 block
            dispatch_group_enter(group)
            // 下载图片缓存图片
            SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (image, error, _, _, _) -> Void in
                
                if image != nil {
                    // 计算当前下载图片的大小
                    dataLength += UIImagePNGRepresentation(image)!.length
                }
                // 出组
                dispatch_group_leave(group)
            })
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("所有的图片都已经下载完成。缓存的图片总大小是：\(dataLength / 1024)kb")
            // 刷新界面
            completion(isSuccessed: true)
        }
    }

}
